package cn.hexcloud.dga.governance.assessor.storage;

import cn.hexcloud.dga.common.constant.MetaConst;
import cn.hexcloud.dga.common.util.StringUtil;
import cn.hexcloud.dga.governance.assessor.Assessor;
import cn.hexcloud.dga.governance.bean.AssessParam;
import cn.hexcloud.dga.governance.bean.GovernanceAssessDetail;
import cn.hexcloud.dga.governance.bean.GovernanceMetric;
import cn.hexcloud.dga.meta.bean.TableMetaInfo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component("LIFE_CYCLE")
public class LifeCycleAssessor extends Assessor {
    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {
        TableMetaInfo tableMetaInfo = assessParam.getTableMetaInfo();
        GovernanceMetric governanceMetric = assessParam.getGovernanceMetric();
        String governanceUrl = governanceMetric.getGovernanceUrl().replace("{tableId}", tableMetaInfo.getId() + "");
        String lifecycleType = tableMetaInfo.getTableMetaInfoExtra().getLifecycleType();
        if (lifecycleType == null || MetaConst.LIFECYCLE_TYPE_UNSET.equals(lifecycleType) || MetaConst.LIFECYCLE_TYPE_OTHER.equals(lifecycleType)) {
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("生命周期类型未设置");
            governanceAssessDetail.setGovernanceUrl(governanceUrl);
        } else if (MetaConst.LIFECYCLE_TYPE_DAY.equals(lifecycleType) ) {
            if(StringUtil.isEmpty(tableMetaInfo.getPartitionColNameJson())){
                governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
                governanceAssessDetail.setAssessProblem("表分区信息未设置");
                governanceAssessDetail.setGovernanceUrl(governanceUrl);
            }else{
                JSONObject metricParamsJsonObj = JSONObject.parseObject(governanceMetric.getMetricParamsJson());
                Long recommendDays = metricParamsJsonObj.getLong("days");
                Long lifecycleDays = tableMetaInfo.getTableMetaInfoExtra().getLifecycleDays();
                if(lifecycleDays > recommendDays){
                    BigDecimal score = BigDecimal.valueOf(recommendDays * 10).divide(BigDecimal.valueOf(lifecycleDays), 2, BigDecimal.ROUND_FLOOR);
                    governanceAssessDetail.setAssessScore(score);
                    governanceAssessDetail.setAssessProblem(String.format("表生命周期长度%d天，超过推荐值(%d天)计%d天",lifecycleDays,recommendDays,lifecycleDays - recommendDays));
                    governanceAssessDetail.setGovernanceUrl(governanceUrl);
                }
            }
        }


    }
}
